package com.eco.fanliapp.utils;



import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created by Mr Zhang on 2017/10/13.
 */
public class Http {

    public static String post(String urlString, String param) {
        String result = null;
        InputStream is = null;
        try {
            URL url = new URL(urlString);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            //post请求需要设置DoOutput为true
            urlConnection.setDoOutput(true);
            urlConnection.setRequestMethod("POST");
            //设置参数

            urlConnection.getOutputStream().write(param.getBytes());
            urlConnection.getOutputStream().flush();
            urlConnection.setConnectTimeout(5 * 1000);
            urlConnection.setReadTimeout(5 * 1000);
            //连接服务器
            urlConnection.connect();
            StringBuilder stringBuilder = new StringBuilder();
            if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                is = urlConnection.getInputStream();
                int len = 0;
                byte[] buffer = new byte[1024];
                while ((len = is.read(buffer)) != -1) {
                    stringBuilder.append(new String(buffer, 0, len));
                }
                result = stringBuilder.toString();
                is.close();
            }

        } catch (MalformedURLException e) {
            ExceptionUtil.errorMsg(HttpUtils.class,e);
        } catch (IOException e) {
            ExceptionUtil.errorMsg(HttpUtils.class,e);
        } finally {
            close(is);
        }
        return result;
    }

 public static String sendHttpPost(String url, String body) throws Exception {
         CloseableHttpClient httpClient = HttpClients.createDefault();
         HttpPost httpPost = new HttpPost(url);
         httpPost.addHeader("Content-Type", "application/json");
         httpPost.setEntity(new StringEntity(body));

         CloseableHttpResponse response = httpClient.execute(httpPost);
         HttpEntity entity = response.getEntity();
         String responseContent = EntityUtils.toString(entity, "UTF-8");

         response.close();
         httpClient.close();
         return responseContent;
         }
    public static String getSource(String urlString) {
        String result = null;
        InputStream in = null;

        try {
            URL url = new URL(urlString);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            //post请求需要设置DoOutput为true
            urlConnection.setRequestMethod("GET");

            //连接服务器
            urlConnection.connect();
            StringBuilder stringBuilder = new StringBuilder();
            if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

                in = urlConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(in));
                int len = 0;
                byte[] buffer = new byte[1024];
                String line = bufferedReader.readLine();
                StringBuffer temp = new StringBuffer();
                while (line != null) {
                    temp.append(line).append("\r\n");
                    line = bufferedReader.readLine();
                }
                bufferedReader.close();
                result = new String(temp.toString().getBytes(), "utf-8");


            }

        } catch (MalformedURLException e) {
            ExceptionUtil.errorMsg(HttpUtils.class,e);
        } catch (IOException e) {
            ExceptionUtil.errorMsg(HttpUtils.class,e);
        } finally {
            close(in);
        }

        return result;
    }


    public static String get(String urlString) {
        String result = null;
        InputStream in = null;

        try {
            URL url = new URL(urlString);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            //post请求需要设置DoOutput为true
            urlConnection.setRequestMethod("GET");
            //连接服务器
            urlConnection.connect();
            StringBuilder stringBuilder = new StringBuilder();
            if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

                in = urlConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(in));
                int len = 0;
                byte[] buffer = new byte[1024];
                String line = bufferedReader.readLine();
                StringBuffer temp = new StringBuffer();
                while (line != null) {
                    temp.append(line).append("\r\n");
                    line = bufferedReader.readLine();
                }
                result = new String(temp.toString().getBytes(), "utf-8");
                bufferedReader.close();

            }

        } catch (MalformedURLException e) {
            ExceptionUtil.errorMsg(HttpUtils.class,e);
        } catch (IOException e) {
            ExceptionUtil.errorMsg(HttpUtils.class,e);
        } finally {
            close(in);
        }

        return result;
    }


    private static void close(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                ExceptionUtil.errorMsg(HttpUtils.class,e);
            }
        }
    }

    public static String subCenter(String str, String a, String b) {
        try {
            String c = str.substring(str.indexOf(a) + a.length());
            return c.substring(0, c.indexOf(b));
        } catch (Exception e) {
            return "";
        }
    }

    public static String getOrderIdByUUId() {
        Date date=new Date();
        DateFormat format = new SimpleDateFormat("yyyyMMdd");
        String time = format.format(date);
        int hashCodeV = UUID.randomUUID().toString().hashCode();
        if (hashCodeV < 0) {//有可能是负数
            hashCodeV = -hashCodeV;
        }
        // 0 代表前面补充0
        // 4 代表长度为4
        // d 代表参数为正数型
        return time + String.format("%011d", hashCodeV);
    }

    public static String InputStream2String(InputStream in) {
        InputStreamReader reader = null;
        try {
            reader = new InputStreamReader(in, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        BufferedReader br = new BufferedReader(reader);
        StringBuilder sb = new StringBuilder();
        String line = "";
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            ExceptionUtil.errorMsg(HttpUtils.class, e);
        }
        return sb.toString();
    }

}
